package com.travelingsalesmen.post;

import com.travelingsalesmen.post.rmi.IServer;
import java.io.File;
import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Manager {

    private static final String PRODUCTS_FILE = "Store" + File.separator + "products.txt";
    private final Store store;

    public Manager(Store store) {
        this.store = store;
    }

    public void openStore() {
        store.open();
    }

    /**
     * Build a catalog by parsing the products text file and adding each item
     *
     * @return a catalog
     * @throws IOException If there is an error in the parsing
     */
    public Catalog buildCatalog() {
        try {
            ProductReader reader = new ProductReader(PRODUCTS_FILE);
            Catalog catalog = new Catalog();
            while (reader.hasMoreProducts()) {
                ProductSpec spec = reader.getNextProduct();
                catalog.add(spec.getUpc(), spec);   //add product spec from file
            }
            return catalog;
        } catch (IOException ex) {
            return null;
        }
    }

    public void startServer() {
        store.startServer();
    }

    public void buildCatalogOnServer() throws RemoteException {
        IServer server = getServer();
        try {
            server.setCatalog(buildCatalog());
        } catch (RemoteException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void logPostIntoServer(IPost post) throws RemoteException {
        IServer server = getServer();
        // server.addPost(post);
        post.connectToServer(server);
    }

    /**
     * @return A reference to the server if it exists and is started
     * @throws RemoteException if the server is not running (properly)
     */
    public IServer getServer() throws RemoteException {
        Registry r = LocateRegistry.getRegistry();
        IServer server;
        try {
            server = (IServer) r.lookup("server");
            return server;
        } catch (NotBoundException ex) {
            throw new RemoteException(ex.getMessage());
        }
    }
}
